package com.wtwd.campus.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.config.ExcelExportStylerConfig;
import com.wtwd.campus.constant.ExcelImportTemplateEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.UUID;

@Component
public class MyExcelUtils {
    private static String filePath;
    private static String excelUrl;
    private static String fileHost;

    @Value("${file.path}")
    public void setFilePath(String param) {
        filePath = param;
    }

    @Value("${excel.url}")
    public void setExcelUrl(String param) {
        excelUrl = param;
    }

    @Value("${file.http}")
    public void setFileHost(String param) {
        fileHost = param;
    }

    private static final String FILE_SUFFIX = ".xlsx";


    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,
                                   String fileName, boolean isCreateHeader, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    public static void downLoadExcelTemplate(List<?> list, String template, Class<?> pojoClass,
                                             HttpServletResponse httpServletResponse) {
        JSONObject jsonObject = JsonConvertUtil.json2Obj("ExcelTemplate.json", JSONObject.class);
        if (jsonObject == null) {
            throw new RuntimeException("模板文件错误");
        }
        JSONObject templateJson = jsonObject.getJSONObject(template);
        String sheetName = templateJson.getString("sheetName");
        String fileName = templateJson.getString("fileName");
        if (StringUtils.isBlank(fileName)) {
            fileName = sheetName;
        }

        if (!fileName.endsWith(FILE_SUFFIX)) {
            fileName = fileName + FILE_SUFFIX;
        }
        JSONObject templateHead = templateJson.getJSONObject("head");
        String headContent = templateHead.getString("content");
        if (StringUtils.isBlank(headContent)) {
            headContent = sheetName;
        }
        ExportParams exportParams = new ExportParams(headContent, sheetName);
        exportParams.setCreateHeadRows(true);
        exportParams.setStyle(ExcelExportStylerConfig.class);
        int titleHeight = 8 * headContent.split("\n").length;
        exportParams.setTitleHeight((short) titleHeight);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, httpServletResponse, workbook);
    }

    public static void downLoadExcelTemplate(int templateCode,
                                             HttpServletResponse httpServletResponse) throws IOException {
        String templateName = ExcelImportTemplateEnum.getTemplateEnum(templateCode).getFileName();
        String fileName = String.join("", templateName, FILE_SUFFIX);
        TemplateExportParams tempParams = new TemplateExportParams(fileName, templateName);
        Workbook workbook = ExcelExportUtil.exportExcel(tempParams, new HashMap<>(1));
        downLoadExcel(fileName, httpServletResponse, workbook);
       /* // 下载本地文件
        String fileName2 = fileName; // 文件的默认保存名
        //从静态资源中获取
        Resource resource = new ClassPathResource(fileName2);
        InputStream inStream = resource.getInputStream();
        // 设置输出的格式
        httpServletResponse.reset();
        httpServletResponse.setContentType("bin");
        httpServletResponse.addHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("utf-8"),"ISO8859-1") + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[150];
        int len;
        try {
            while ((len = inStream.read(b)) > 0) {
                httpServletResponse.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }

    public static String exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
                                     HttpServletResponse response) {
        return defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }


    private static String defaultExport(List<?> list, Class<?> pojoClass, String fileName,
                                        HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        FileOutputStream fileOutputStream = null;
        String excelname = UUID.randomUUID() + ".xls";
        String path = filePath + excelUrl + excelname;
        File file = new File(filePath + excelUrl);
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            fileOutputStream = new FileOutputStream(path);
            workbook.write(fileOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileHost + excelUrl + excelname;
    }

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setCharacterEncoding("UTF-8");
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /*   private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
           Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
           if (workbook != null) ;
           downLoadExcel(fileName, response, workbook);
       }*/
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)
            throws Exception {
        if (file == null) {
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
            throw new Exception("excel文件不能为空");
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return list;
    }
}
